#pragma once
#include <iostream>
#include <vector>
#include <semaphore.h>


namespace ns_ring_queue
{
    const int g_cap_default = 10;
    template <class T>
    class RingQueue
    {
    private:
        std::vector<T> _ring_queue;
        int _cap;
        sem_t _blank_sem;
        sem_t _data_sem;
        int _c_step;
        int _p_step;
        
        pthread_mutex_t _c_mtx;
        pthread_mutex_t _p_mtx;


    public:
        RingQueue(int cap = g_cap_default) : _cap(cap), _ring_queue(cap)
        {
            sem_init(&_blank_sem, 0, cap);
            sem_init(&_data_sem, 0, 0);
            _c_step = _p_step = 0;
            pthread_mutex_init(&_c_mtx, nullptr);
            pthread_mutex_init(&_p_mtx, nullptr);

        };
        ~RingQueue()
        {
            sem_destroy(&_blank_sem);
            sem_destroy(&_data_sem);
            pthread_mutex_destroy(&_c_mtx);
            pthread_mutex_destroy(&_p_mtx);
        };

    public:
        void Pop(T *out)
        {
            sem_wait(&_data_sem);

            pthread_mutex_lock(&_c_mtx);
            *out = _ring_queue[_c_step];
            _c_step++;
            _c_step %= _cap;
            pthread_mutex_unlock(&_c_mtx);

            sem_post(&_blank_sem);
        }
        void Push(const T &in)
        {
            sem_wait(&_blank_sem);

            pthread_mutex_lock(&_p_mtx);
            _ring_queue[_p_step] = in;
            _p_step++;
            _p_step %= _cap;
            pthread_mutex_unlock(&_p_mtx);

            sem_post(&_data_sem);
        }
    };

}